﻿using System;
using NHibernate;
using NHibernate.Cfg;

namespace ParaEditor.Common.NHibernate
{
    public class NHibernateHelper
    {
        private ISessionFactory _sessionFactory;

        private ISessionFactory _sessionFactorySource;

        public NHibernateHelper()
        {
            if (_sessionFactory == null)
            {
                _sessionFactory = GetSessionFactory();
            }
            if (_sessionFactorySource == null)
            {
                _sessionFactorySource = GetSessionFactorySource();
            }
        }

        private ISessionFactory GetSessionFactory()
        {
            try
            {
                string FileName = AppDomain.CurrentDomain.BaseDirectory;
                FileName = FileName + @"hibernate.cfg.xml";
                //return new Configuration().Configure(FileName).BuildSessionFactory();
                Configuration cfg = new Configuration();
                cfg.Configure(FileName);
                return cfg.BuildSessionFactory();
            }
            catch (Exception e)
            {
                //throw e;
            }
            return _sessionFactory;
            //return new Configuration().Configure().BuildSessionFactory();
        }

        private ISessionFactory GetSessionFactorySource()
        {
            try
            {
                string FileName = AppDomain.CurrentDomain.BaseDirectory;
                FileName = FileName + @"hibernate_source.cfg.xml";
                //return new Configuration().Configure(FileName).BuildSessionFactory();
                Configuration cfg = new Configuration();
                cfg.Configure(FileName);
                return cfg.BuildSessionFactory();
            }
            catch (Exception e)
            {
                //throw e;
            }
            return _sessionFactorySource;
            //return new Configuration().Configure().BuildSessionFactory();
        }


        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }

        public ISession GetSessionSource()
        {
            return _sessionFactorySource.OpenSession();
        }
    }
}
